package cn.lixu.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * @author LiXu
 * @date 2022/08/22 0022 15:29:09
 */

public class RequestTimeFilter implements GatewayFilter, Ordered {

    //打印日志，类似于slf4j
    private static final Logger log = LoggerFactory.getLogger(RequestTimeFilter.class);

    /**
     * @author lixu
     * @data 2022/08/22 0022 15:35:47
     * @param: null
     * @return: null
     * ServerWebExchange exchange  上下文对象
     * GatewayFilterChain chain  调用链对象
     **/
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取地址
        String path = exchange.getRequest().getURI().getPath();
        log.info("请求执行的路径：{}", path);
        //将开始的时间存入map
        exchange.getAttributes().put("startTime", new Date().getTime());
        // 执行完成之后
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    // 开始时间
                    Long startTime = exchange.getAttribute("startTime");
                    // 结束时间
                    Long endTime = (System.currentTimeMillis() - startTime);
                    // 打印当前请求耗时
                    log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                })
        );
    }

    //执行的优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
